package com.hong.springcloud.controller;

import com.hong.springcloud.entity.Product;
import com.hong.springcloud.service.ProductService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by John on 2018/11/25.
 */
@RestController
public class ProductController {

    @Autowired
    private ProductService productService;

    @Autowired
    private DiscoveryClient client;

    @RequestMapping(value = "/product/add", method = RequestMethod.POST)
    public int add(@RequestBody Product product)
    {
        return productService.add(product);
    }

    @RequestMapping(value = "/product/get/{id}", method = RequestMethod.GET)
    public Product get(@PathVariable("id") Long id)
    {
        return productService.get(id);
    }

    @RequestMapping(value = "/product/list", method = RequestMethod.GET)
    public Map<String,Object> list()
    {
        Map<String,Object> resultMap = new HashMap<>(2);
        resultMap.put("instance-id","microservice-product-8001");
        resultMap.put("data",productService.list());
        return resultMap;
    }

    @RequestMapping(value = "/product/discovery", method = RequestMethod.GET)
    public Object discovery()
    {
        List<String> list = client.getServices();
        System.out.println("**********" + list);

        List<ServiceInstance> srvList = client.getInstances("MICROSERVICE-PRODUCT");
        for (ServiceInstance element : srvList) {
            System.out.println(element.getServiceId() + "\t" + element.getHost() + "\t" + element.getPort() + "\t"
                    + element.getUri());
        }
        return this.client;
    }
}
